package com.dingreading.cloud.subject.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dingreading.cloud.common.base.R;
import com.dingreading.cloud.common.util.AccountUtil;
import com.dingreading.cloud.common.util.HttpUtils;
import com.dingreading.cloud.common.util.IpUtil;
import com.dingreading.cloud.common.util.RedisParam;
import com.dingreading.cloud.subject.dto.SubjectLessonDto;
import com.dingreading.cloud.subject.dto.SubjectLessonListDto;
import com.dingreading.cloud.subject.entity.Stores;
import com.dingreading.cloud.subject.entity.SubjectLessonLog;
import com.dingreading.cloud.subject.entity.Subjects;
import com.dingreading.cloud.subject.service.StoresService;
import com.dingreading.cloud.subject.service.SubjectLessonLogService;
import com.dingreading.cloud.subject.service.SubjectLessonService;
import com.dingreading.cloud.subject.service.SubjectsService;
import com.dingreading.cloud.subject.util.SubjectUtil;
import com.dingreading.cloud.subject.util.TreeJsonUtil;
import com.dingreading.cloud.subject.util.redis.RedisService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RefreshScope
@RestController
@RequestMapping("/front/douXueHui")
@Api(tags = "门店-兜学慧学科管理")
public class FrontDouXueHuiController {

    @Resource
    private SubjectsService subjectsService;
    @Resource
    private SubjectLessonService subjectLessonService;
    @Resource
    private StoresService storesService;
    @Resource
    private SubjectLessonLogService subjectLessonLogService;
    @Resource
    private RedisService redisService;

    @Value("${subjectUrl}")
    private String subjectUrl;
    @Value("${lessonPdfFileUrl}")
    private String lessonPdfFileUrl;


    @ApiOperation(value = "兜学慧学科列表")
    @PostMapping(value = "/subjectList")
    public R<Object> subjectList(
            @ApiParam(value = "公司uid") @RequestParam(value = "corpUid") String corpUid,
            @ApiParam(value = "门店uid") @RequestParam(value = "storeUid") String storeUid,
            @ApiParam(value = "门店名称") @RequestParam(value = "storeName") String storeName,
            @ApiParam(value = "员工uid") @RequestParam(value = "staffUid") String staffUid,
            @ApiParam(value = "员工姓名") @RequestParam(value = "staffName") String staffName
    ) {
        Stores stores = storesService.getByCorpUidAndStoreUid(null, storeUid);
        if (!stores.getCooperationType().contains("50"))
            return R.fail("门店没有此合作权限");

        String redisKey = RedisParam.DXH_SUBJECT;
        String json = (String) redisService.get(redisKey);

        JSONArray treeJson = new JSONArray();
        if (StringUtils.isNotBlank(json)) {
            // 获取redis缓存数据
            treeJson = JSONArray.parseArray(json);
        } else {
            List<Subjects> subjectsList = subjectsService.dxhListByMainId(174L);
            if (CollectionUtils.isNotEmpty(subjectsList)) {
                treeJson = TreeJsonUtil.createTreeJson(subjectsList);
                // 缓存2小时
                redisService.set(redisKey, treeJson.toJSONString(), 7200);
            }
        }

        return R.ok(treeJson);
    }


    @ApiOperation(value = "获取学科下的课次列表")
    @PostMapping(value = "/getSubjectLessons")
    public R<Object> getSubjectLessons(
            @ApiParam(value = "公司uid") @RequestParam(value = "corpUid") String corpUid,
            @ApiParam(value = "门店uid") @RequestParam(value = "storeUid") String storeUid,
            @ApiParam(value = "门店名称") @RequestParam(value = "storeName") String storeName,
            @ApiParam(value = "员工uid") @RequestParam(value = "staffUid") String staffUid,
            @ApiParam(value = "员工姓名") @RequestParam(value = "staffName") String staffName,
            @ApiParam(value = "学科id") @RequestParam(value = "subjectId") Long subjectId
    ) {
        Subjects subjects = subjectsService.getById(subjectId);
        if (subjects == null) return R.fail("学科获取失败");
        if (!subjects.getDxhEnabled().equals(1)) return R.fail("学科已被禁用");
        if (!subjects.getLevelEnd().equals(1)) return R.fail("学科不是最后一级");

        long power = 0;
        if (subjects.getFreeStatus() != null && subjects.getFreeStatus().equals(1)) {
            // 是体验学科并且是体验账号，则有权限
            power = 1;
        } else {
            // 非体验学科并且不是体验账号，则有权限
            if (!AccountUtil.isTyUser(corpUid)) {
                power = 1;
            }
        }

        List<SubjectLessonListDto> lessonList = subjectLessonService.getSubjectLessonNoUrl(subjectId);
        for (SubjectLessonListDto lessonDto : lessonList) {
            lessonDto.setPower(power);
            if (power != 1)
                lessonDto.setDataUrl(null);
            boolean b = lessonDto.getDownloadStatus() != null;
            lessonDto.setDownloadStatus(b);
        }

        return R.ok(lessonList);
    }


    @ApiOperation(value = "获取课次信息")
    @PostMapping(value = "/v2/getById")
    public R<Object> getByIdV2(
            HttpServletRequest request,
            @ApiParam(value = "公司uid") @RequestParam(value = "corpUid") String corpUid,
            @ApiParam(value = "门店uid") @RequestParam(value = "storeUid") String storeUid,
            @ApiParam(value = "门店名称") @RequestParam(value = "storeName") String storeName,
            @ApiParam(value = "员工uid") @RequestParam(value = "staffUid") String staffUid,
            @ApiParam(value = "员工姓名") @RequestParam(value = "staffName") String staffName,
            @ApiParam(value = "课次id") @RequestParam(value = "id") Long id
    ) {
        SubjectLessonDto lessonDto = subjectLessonService.getDtoById(id);
        if (lessonDto == null) return R.fail("课次获取失败");
        if (!lessonDto.getEnabled().equals(1)) return R.fail("课次已被禁用");

        Subjects subjects = subjectsService.getById(lessonDto.getSubjectId());
        if (subjects == null) return R.fail("关联学科获取失败");
        if (!subjects.getDxhEnabled().equals(1)) return R.fail("关联学科已被禁用");
        if (subjects.getFreeStatus() == null || !subjects.getFreeStatus().equals(1)) {
            // 非体验学科并且是体验账号，则没有有权限
            if (AccountUtil.isTyUser(corpUid)) {
                return R.fail("没有访问权限");
            }
        }

        String teachPlanUrl = lessonDto.getTeachPlanUrl();
        // 获取备课服务器访问地址
        if (StringUtils.isNotBlank(teachPlanUrl)) {
            lessonDto.setTeachPlanUrl(lessonPdfFileUrl.concat(teachPlanUrl));
        }
        if (StringUtils.isNotBlank(lessonDto.getHtmlUrl())) {
            lessonDto.setHtmlUrl(subjectUrl.concat(lessonDto.getHtmlUrl()) + "?" + System.currentTimeMillis());
        }
        lessonDto.setDataUrl(null);

        // 根据兜学慧的课次id获取说课和教学视频
        setDxhVideoList(lessonDto);

        // 课件访问记录
        String ip = IpUtil.getIpAddr(request);
        SubjectLessonLog log = SubjectUtil.saveLog(corpUid, storeUid, staffUid, staffName, ip, 1, lessonDto.getUid(), "");
        subjectLessonLogService.saveOrUpdate(log);

        return R.ok(lessonDto);
    }

    @ApiOperation(value = "获取教研视频")
    @PostMapping(value = "/getVideoList")
    public R<Object> getVideoList(
            HttpServletRequest request,
            @ApiParam(value = "公司uid") @RequestParam(value = "corpUid") String corpUid,
            @ApiParam(value = "门店uid") @RequestParam(value = "storeUid") String storeUid,
            @ApiParam(value = "门店名称") @RequestParam(value = "storeName") String storeName,
            @ApiParam(value = "员工uid") @RequestParam(value = "staffUid") String staffUid,
            @ApiParam(value = "员工姓名") @RequestParam(value = "staffName") String staffName,
            @ApiParam(value = "课次id") @RequestParam(value = "id") Long id
    ) {
        return subjectLessonService.getDouXueHuiVideoList(request, corpUid, storeUid, storeName, staffUid, staffName, id);
    }

    /**
     * 根据兜学慧的课次id获取说课和教学视频
     */
    private void setDxhVideoList(SubjectLessonDto lessonDto) {
        if (lessonDto.getDxhLessonId() != null && lessonDto.getDxhLessonId() > 0) {
            String dxhVideoUrl = "https://chineseapi.xiaoyuxiang.com:8300/castle-provider-teaching/front/data/dataLesson/v2/getVideoListById";
            Map<String, String> map = new HashMap<>();
            map.put("id", String.valueOf(lessonDto.getDxhLessonId()));

            String result = HttpUtils.post(dxhVideoUrl, map);
            if (StringUtils.isNotBlank(result)) {
                JSONObject jsonObject = JSONObject.parseObject(result);
                Integer status = jsonObject.getInteger("status");
                if (status != null && status.equals(200)) {
                    JSONArray speakVideoList = jsonObject.getJSONArray("speakVideoList");
                    JSONArray teachVideoList = jsonObject.getJSONArray("teachVideoList");

                    lessonDto.setTeachVideoList(teachVideoList);
                    lessonDto.setSpeakVideoList(speakVideoList);
                }
            }
        }
    }

}